<template>
<div>
	<div >
		<img v-if="imageUrl && !drawing && abPermission!='n'" style="width: 220px; height: 110px"  :src="imageUrl"  alt="签名" />
		 <x-button v-if="abPermission=='w' || abPermission=='b'" mini type="primary" class="fa fa-pencil" v-show="imageUrl" @click.native="drawing = true">重签</x-button> 
		 <x-button v-if="abPermission=='w' || abPermission=='b'" mini type="primary" class="fa fa-pencil" v-show="!imageUrl" @click.native="drawing = true">签字</x-button>
		 <x-button v-if="imageUrl && (abPermission==='w' || abPermission==='b')" mini type="warn" class="fa fa-remove" @click.native="remove()">删除</x-button>
		 
		 <popup v-model="drawing" position="left" width="100%" >
			<div v-if="drawing"  id="drawing" >
				<VueSignaturePad  ref="signaturePad" :width="drawWidth" :height="drawHeight" style="margin: 0 auto;"/>
				<div>
					<x-button mini plain  type="primary"  @click.native="save">保存</x-button> 
					<x-button mini plain  type="warn"  @click.native="drawing = false">取消</x-button> 
					<x-button mini plain  type="default"  @click.native="undo">撤销</x-button> 
					<x-button mini plain  type="default"  @click.native="clear">清楚</x-button> 
				</div>
			</div>
		</popup>
	</div>
</div>
</template>

<script>
import VueSignaturePad from 'vue-signature-pad';
import Vue from 'vue';
Vue.use(VueSignaturePad);
	export default {
		name:"abSignature",
		props:{
			columnName:{// 字段名字
				type:String,
				default:"签字"
			},
			// 业务数据
			value:{},
			abPermission:{
				type:String,
				default:"w"
			}
		},
		data(){
			return {
				signature:{},
				drawing : false,
				imageUrl:'',
				drawHeight:'',
				drawWidth:'98%'
			}
		},
		watch:{
			'drawing' :function(value){
			 	if(value){
			 		window.setTimeout(()=>{
			 			if (window.orientation === 180 || window.orientation === 0) {
			 			 this.$vux.toast.text('建议使用横屏模式签字', 'top');
			 			}
			 		},1000)
			 	}
			}
		},
		created(){
			if(this.value){
				this.signature = JSON.parse(this.value);
				this.setImageUrl();
			}
			
			this.setImageUrl();
			
			var that = this;
			window["onorientationchange"] = function() {
				that.changeWidth();
				if(!that.drawing)return;
				that.drawing = false;
				window.setTimeout(()=>{
					that.changeWidth();
					that.drawing = true;
		 		},1000)
	        }
			that.changeWidth();
		},
		methods:{
			changeWidth(){
				var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
				var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
				if(windowWidth > window.screen.width){
					windowWidth = window.screen.width;
				}
				if(windowHeight > window.screen.height){
					windowHeight = window.screen.height;
				}
				// 宽度大于高度的2倍
				if(windowWidth/2 > (windowHeight-50)){
					this.drawHeight =  (windowHeight-50) + 'px';
					this.drawWidth = (windowHeight-50)*2 + 'px';
				}else{
					this.drawHeight = (windowWidth/2) + 'px';
					this.drawWidth =  windowWidth + 'px';
				}
				
			/* 	
				let height = 0
				if (window.orientation === 90){
					height = windowHeight -50 ;
				}else{
					height = windowWidth *3/4  
				} */
				return;
			},
			remove(){
				this.imageUrl = '';
				this.signature = {};
				this.$emit('input',"");
			},
			undo() {
		        this.$refs.signaturePad.undoSignature();
		      },
		      save() {
		        const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
		        if(isEmpty){
		        	this.$vux.toast.show({  text: '请签字', type:'warn' })
					return;
		        }
		        
		        this.$vux.loading.show({  text: '保存中..' })
		        	
		        var form = new window.FormData();
		        var blobData = this.dataURItoBlob(data);
		        form.append("file",blobData , this.columnName +".png");
		        
		        var xhr = new XMLHttpRequest();
		        xhr.withCredentials = true;
		        xhr.open('POST', Vue.__ctx +"/sys/sysFile/upload");
		        
		        xhr.responseType = 'json';
		        xhr.send(form);
		        
		        const that = this;
		        xhr.onload = function () {
		           that.$vux.loading.hide();
    	           console.log(this.response);
    	           if(this.response.isOk){
    	        	   that.signature.id = this.response.data;
    	        	   that.signature.name = that.columnName;
    	        	   that.drawing = false;
    	        	   that.setImageUrl();
    	        	   that.$emit('input', JSON.stringify(that.signature));
    	           }else{
    	        	   that.$vux.toast.show({  text: '保存失败，请联系管理员。', type:'warn' }) 
    	           }
      	        }
		        console.log(data);
		      },
		      clear(){
		    	  this.$refs.signaturePad.clearSignature();
		      },
		       dataURItoBlob(dataURI) {
		          var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
		          var byteString = atob(dataURI.split(',')[1]); //base64 解码
		          var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
		          var intArray = new Uint8Array(arrayBuffer); //创建视图

		          for (var i = 0; i < byteString.length; i++) {
		              intArray[i] = byteString.charCodeAt(i);
		          }
		          return new Blob([intArray], {type: mimeString});
		      },
		      setImageUrl(){
		    	  if(this.signature.id){
		    		  this.imageUrl = this.__ctx + '/sys/sysFile/download?fileId=' + this.signature.id;
			    	}
		      },
		},
		computed: {
		},
		mounted:function(){
			// 移除掉外部css 
			this.$el.className = ""
		}
	}
</script>

<style>
canvas {
	padding: 4px;
    border-radius: 4px;
    border: 1px solid #ddd;
    line-height: 1;
    display: block;
    box-shadow: 0 1px 1px rgba(0,0,0,0.075);
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.075);
    -moz-box-shadow: 0 1px 1px rgba(0,0,0,0.075);
}
#drawing {
	font-family: "Avenir", Helvetica, Arial, sans-serif;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
	text-align: center;
	color: #2c3e50;
}

</style>
